package io.mvvm.security.service.impl;

import io.mvvm.common.entity.SelfUserDetails;
import io.mvvm.security.service.IUserDetailsService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: seize-login
 * @description:
 * @author: 潘
 * @create: 2021-05-14 23:12
 **/
@Service("userDetailsService")
public class UserDetailsServiceImpl implements IUserDetailsService {


    // 用户表
    private static List<SelfUserDetails> dbUserList = new ArrayList<>();

    // 用户角色表
    private static Map<String, Set<GrantedAuthority>> userRoles = new HashMap<>();

    // 角色菜单表
    private static Map<String, Set<String>> roleMenus = new HashMap<>();

    // 构建角色
    static {
        Set<GrantedAuthority> rootRoles = new HashSet<>();
        GrantedAuthority ga = new SimpleGrantedAuthority("root");
        rootRoles.add(ga);
        Set<GrantedAuthority> adminRoles = new HashSet<>();
        GrantedAuthority ga1 = new SimpleGrantedAuthority("admin");
        adminRoles.add(ga1);
        userRoles.put("root", rootRoles);
        userRoles.put("admin", adminRoles);
    }

    // 构建用户
    static {
        SelfUserDetails sd = new SelfUserDetails();
        sd.setUsername("root");
        sd.setPassword("$2a$10$e7JMhF0SOAbQc57tDKbCkOqJ6bOFb1u6/BwCbNkU7bY1z5OEIuiEe");
        sd.setAuthorities(userRoles.get("root"));

        SelfUserDetails sd1 = new SelfUserDetails();
        sd1.setUsername("admin");
        sd1.setPassword("$2a$10$e7JMhF0SOAbQc57tDKbCkOqJ6bOFb1u6/BwCbNkU7bY1z5OEIuiEe");
        sd1.setAuthorities(userRoles.get("admin"));

        dbUserList.add(sd);
        dbUserList.add(sd1);
    }

    // 构建角色菜单
    static {
        Set<String> root = new HashSet<>();
        root.addAll(Arrays.asList("/userTest/add", "/root/**"));
        roleMenus.put("root", root);
        Set<String> admin = new HashSet<>();
        admin.addAll(Arrays.asList("/adminTest/add", "/admin/**"));
        roleMenus.put("admin", admin);
        Set<String> common = new HashSet<>();
        common.addAll(Arrays.asList("/commonTest/add", "/common/**", "/forciblyLogin"));
        roleMenus.put("common", common);

    }

    // 按照用户名查询用户信息包含角色
    @Override
    public UserDetails loadUserByUsername(String username) {

        return dbUserList.stream()
                .filter(e -> e.getUsername().equals(username))
                .findFirst().orElse(null);

    }

    @Override
    public Set<String> getRolesByUrl(String url) {
        return null;
    }
}
